<?php

namespace App\Service;

use App\Library\Requests\Withdraw\StoreWithdrawApplyRequest;
use App\Library\Requests\Withdraw\StoreWithdrawPageRequest;
use App\Library\YsdLib;
use App\Logic\AmountLogic;
use App\Logic\PaymentMethodLogic;
use App\Logic\StoreLogic;
use App\Logic\WithdrawLogic;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class WithdrawService extends StoreBaseService
{
    /**
     * logic
     * @return WithdrawLogic
     */
    private function logic(): WithdrawLogic
    {
        if (empty($this->logic)) $this->logic = new WithdrawLogic;
        return $this->logic;
    }

    /**
     * paging
     * @param StoreWithdrawPageRequest $request
     * @return JsonResponse
     */
    public function paging(StoreWithdrawPageRequest $request): JsonResponse
    {
        return success($this->logic()->paging($request));
    }

    /**
     *
     * @param StoreWithdrawApplyRequest $request
     * @return JsonResponse
     * @throws Exception
     * @Author Sun Wu
     *
     */
    public function apply(StoreWithdrawApplyRequest $request): JsonResponse
    {
        if ($request->paymentMethodType !== 'alipay') $request->paymentMethodType = 'alipay';
        $paymentMethod = PaymentMethodLogic::findByScope('key', $request->paymentMethodType);
        if (is_null($paymentMethod)) return failMessage('提现方式错误');
        $store = StoreLogic::detail(staff('storeId'));
        if ($store->status === 0) return failMessage('账号不可用');
        else if (is_null($store->identity)) return failMessage('提现账号不存在');
        $scan = AmountLogic::entered(staff('store.user_id'));
        if ($scan < $request->amount) return failMessage('账户余额不足');
        $fee = bcmul(bcdiv(l('base.storeWithdrawRatio'), 100, 2), $request->amount, 2);
        $withdraw = WithdrawLogic::insertForModel([
            'es' => es(),
            'userTypeId' => userTypeId(),
            'userId' => $store->user_id,
            'paymentMethodId' => $paymentMethod->id,
            'name' => $store->id_name,
            'identity' => $store->identity,
            'amount' => bcsub($request->amount, $fee, 2),
            'fee' => $fee,
            'config' => YsdLib::getConfig($paymentMethod->id),
        ]);
        AmountLogic::insertForModelOfLock([
            'title' => '提现',
            'amountType' => 'withdraw',
            'storeId' => staff('storeId'),
            'objectId' => $withdraw->id,
            'objectType' => 'withdraw',
            'amount' => -$request->amount,
            'description' => '提现',
            'extend' => ['fee' => $fee],
        ]);
        remind(config('app.name') . ucfirst($this->logic()->getTable()));
        return success();
    }
}
